<?php

namespace app\api\controller\web;


use app\admin\model\project\Job;
use app\admin\model\project\Project;
use app\admin\model\User;
use app\admin\model\UserMsg;
use app\common\common\PerServer;
use app\common\controller\Api;
use app\common\helpers\ImageUtil;
use think\Cache;
use think\Config;
use think\Db;
use think\db\Query;
use think\Exception;
use think\Model;


class Common extends Api
{
    protected $noNeedLogin = ['areaList','dataOverview','jobList','pushMsg','msgDetails','cs','getApp'];
    protected $noNeedRight = '*';
    protected $model ='';
    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     *
     * 获取微信公众号id 传给 bindWechat.html 页面
     */
    public function getApp(){
        $appid = config('wx.GzhAppID');
         echo "var appid="."'$appid';";
    }

    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 省份列表
     */
    public function areaList()
    {
        $list = Db::name('area')->field('id,name')->where('level','1')->select();
        $this->success("获取成功",$list);
    }

    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 数据总览
     */
    public function dataOverview(){
        $info = (new Project())->field('count(1) as project_num,  
            IFNULL(sum(zj_num),0) as zj_num,
            IFNULL(sum(if(filings_status = 1,1,0)),0) as filings_num,
            IFNULL(sum(if(approval_status = 1,1,0)),0) as approval_num,
            IFNULL(sum(if(pay_status = 1,1,0)),0) as pay_num,
            IFNULL(sum(if(pay_status = 1,pay_money,0)),0) as pay_money,
            IFNULL(sum(if(status = 2,1,0)),0) as js_num,
            IFNULL(sum(if(status = 3,1,0)),0) as yzz_num')->where('is_del','=','0')->find();
        $this->success("获取成功",$info);;
    }


    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 数据统计
     */
    public function dataStatistics(){

        $user = $this->auth->getUserinfo();
        $where['is_del']=0;
        if(!PerServer::getInstance()->isAuth(3)){ //看权限返回数据
            $where['user_id'] = $user['user_id'];
        }
        $area_id = $this->request->param('area_id');//区域
        $subject_id = $this->request->param('subject_id');//主体
        $type_id = $this->request->param('type_id');//类型
        $search = $this->request->param('search');//
        $where['is_del']=0;
        if($subject_id){
            $where['subject_id'] = $subject_id;
        }
        if($area_id){
            $where['area_id'] = $area_id;
        }
        if($type_id){
            $where['type_id'] = $type_id;
        }
        if($search){
            $where['project_name'] = ['like','%'.$search.'%'];
        }
        $info = (new Project())->field('count(1) as project_num,  
            IFNULL(sum(zj_num),0) as zj_num,
            IFNULL(sum(if(filings_status = 1,1,0)),0) as filings_num,
            IFNULL(sum(if(approval_status = 1,1,0)),0) as approval_num,
            IFNULL(sum(if(pay_status = 1,1,0)),0) as pay_num,
            IFNULL(sum(if(pay_status = 1,pay_money,0)),0) as pay_money,
            IFNULL(sum(if(status = 2,1,0)),0) as js_num,
            IFNULL(sum(if(status = 3,1,0)),0) as yzz_num')->where($where)->find();
        $this->success("获取成功",$info);
    }


    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 职位列表
     */
    public function jobList()
    {
        $list = (new Job())->order('id desc')->select();
        $this->success("获取成功",$list);
    }


    /**
     * @throws Exception
     * 发送消息
     */
    public function pushMsg(){
        $user = $this->auth->getUserinfo();
        $validate = new \think\Validate([
            ['project_id', 'require', '项目不能为空'],
            ['content', 'require', '发送内容不能为空'],
            ['user_list', 'require', '请选择发送人不能为空'],
        ]);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $project_id = $this->request->param('project_id');
        $content = $this->request->param('content');
        $user_list = $this->request->param('user_list');
        $data=[
            'push_user_id'=>$user['user_id'],
            'content'=>$content, //消息内容
            'project_id'=>$project_id,
            'createtime'=>date('Y-m-d H:i:s'), //上传时间
            'user_list'=>$user_list,
        ];
        $user_arr = explode(',',$user_list);
        $user_total = (new User())->where('id','in',$user_arr)->count();
        if(count($user_arr) != $user_total){
            $this->error("选择的用户不存在");
        }

        $template_num = Cache::get(TEMPLATE1);

        $project =  (new \app\admin\model\Project())->alias('p')
            ->join('type t','t.id=p.type_id','left')
            ->where('p.id',$project_id)
            ->find();
        Db::startTrans();
        try {
            Db::commit();
            Db::name('user_msg')->insert($data);
            $last_id = Db::name('user_msg')->getLastInsID();
            foreach ($user_arr as $v){
                $data1[]=[
                    'msg_id'=>$last_id,
                    'accept_user_id'=>$v,
                    'project_id'=>$project_id,
                ];

                $userInfo = \app\common\model\User::get($v);
                if($userInfo['wechat_openid'] && $userInfo['is_follow'] == 1 && $template_num < 60){
                    $data2=[
                        "first"=> "您好，您收到一张工单通知",
                        "keyword1"=> $project['type_name'],
                        "keyword2"=> $project['project_name'],
                        "keyword3"=>$project['project_leader'],
                        "keyword4"=> $content,
                        "remark"=> "收到该通知后请及时跟进",
                    ];
                    Cache::set(TEMPLATE1,$template_num+1,90);
                    sendMessage($userInfo['wechat_openid'],$data2,TEMPLATE1);
                }
            }
            Db::name('user_msg_log')->insertAll($data1);
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success("发送成功");
    }

    /**
     * @throws Exception
     * 我收到的消息列表
     */
    public function receiveMsgList(){

        $user = $this->auth->getUserinfo();
        $page = $this->request->param('page',1);//页码
        $pageSize = $this->request->param('pageSize',10);//每页展示数量
        $model = (new UserMsg())->alias('m')
            ->field('ml.id,u.realname,project_logo,project_name,project_no,m.content,m.createtime,is_read')
            ->join('user_msg_log ml','m.id = ml.msg_id','left')
            ->join('project p','m.project_id = p.id','left')
            ->join('user u','m.push_user_id = u.id','left')
            ->where('accept_user_id',$user['id'])
            ->order('m.createtime desc')
            ->paginate($pageSize, '', ['page' => $page, 'list_rows' => $pageSize]);

        $total= $model->total();

        $list =  $model->items();
        if($list){
            foreach ($list as $v){
                $v['project_logo'] = ImageUtil::handle($v['project_logo']);
            }
        }
        $result = array("total" =>$total , "list" => $list);
        $this->success("获取成功",$result);;

    }

    /**
     * @throws Exception
     * 我收到的消息详情
     */
    public function msgDetails(){

        $msg_id = $this->request->param('id');
        $user = $this->auth->getUserinfo();
        $ret = Db::name('user_msg')->alias('m')
            ->field('u.realname,u.avatar,m.project_id,project_logo,project_name,project_no,m.content,m.createtime,is_read')
            ->join('user_msg_log ml','m.id = ml.msg_id')
            ->join('project p','m.project_id = p.id')
            ->join('user u','m.push_user_id = u.id')
            ->where(['ml.id'=>$msg_id,'accept_user_id'=>$user['id']])->find();
        if($ret){
            $ret['project_log'] = ImageUtil::handle($ret['project_logo']);
            $ret['avatar'] = ImageUtil::handle($ret['avatar']);
            if($ret['is_read'] == '0'){
                Db::name('user_msg_log')
                    ->where(['id'=>$msg_id,'accept_user_id'=>$user['id']])
                    ->update(['is_read'=>1,'readtime'=>date('Y-m-d H:i:s')]);
            }
            $this->success("获取成功",$ret);
        }else{
            $this->success("获取失败");
        }

    }


    /**
     * @throws Exception
     * 我推送的消息列表
     */
    public function pushMsgList(){
        $user = $this->auth->getUserinfo();
        $page = $this->request->param('page',1);//页码
        $pageSize = $this->request->param('pageSize',10);//每页展示数量
        $model = (new UserMsg())->alias('m')
            ->field('m.id,u.realname,project_logo,project_name,project_no,m.content,m.createtime,user_list')
            ->join('project p','m.project_id = p.id','left')
            ->join('user u','m.push_user_id = u.id','left')
            ->where('push_user_id',$user['id'])
            ->order('m.createtime desc')
            ->paginate($pageSize, '', ['page' => $page, 'list_rows' => $pageSize]);

        $total= $model->total();
        $list =  $model->items();
        $userList =   collection((new User())->field('id,realname')->select())->toArray();
        $userList = array_column($userList,'realname','id');
        if($list){
            foreach ($list as &$v){
                $v['project_logo'] = ImageUtil::handle($v['project_logo']);
                $user_list_arr = [];
                if($v['user_list']){
                    $userArr = explode(',',$v['user_list']);
                    foreach ($userArr as $vs){
                        if(isset($userList[$vs])){
                            $user_list_arr[] = $userList[$vs];
                        }
                    }
                }
                $v['user_list_arr'] = $user_list_arr;
            }
        }
        $result = array("total" =>$total , "list" => $list);
        $this->success("获取成功",$result);;

    }

    /**
     * @throws Exception
     * 我推送的消息详情
     */
    public function pushMsgDetails(){

        $msg_id = $this->request->param('id');
        $user = $this->auth->getUserinfo();
        $ret = Db::name('user_msg')->alias('m')
            ->field('u.realname,m.project_id,project_logo,project_name,project_no,m.content,m.createtime,user_list')
            ->join('project p','m.project_id = p.id')
            ->join('user u','m.push_user_id = u.id')
            ->where(['m.id'=>$msg_id,'push_user_id'=>$user['id']])->find();
        if($ret){
            $userList =   collection((new User())->field('id,realname')->select())->toArray();
            $userList = array_column($userList,'realname','id');
            $ret['project_log'] = ImageUtil::handle($ret['project_logo']);
            $user_list_arr = [];
            if($ret['user_list']){
                $userArr = explode(',',$ret['user_list']);
                foreach ($userArr as $vs){
                    if(isset($userList[$vs])){
                        $user_list_arr[] = $userList[$vs];
                    }
                }
            }
            $ret['user_list_arr'] = $user_list_arr;
            $this->success("获取成功",$ret);
        }else{
            $this->success("获取失败");
        }

    }


    /**
     * @throws Exception
     * 我收到的未读消息条数
     */
    public function myUnreadCount(){
        $user = $this->auth->getUserinfo();
        $total = (new UserMsg())->alias('m')
            ->join('user_msg_log ml','m.id = ml.msg_id','left')
            ->where('accept_user_id',$user['id'])
            ->where('is_read','0')
            ->count();
        $this->success("获取成功",$total);;

    }


}
